package com.gowow.gowoworionapp.network;


import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitClient {
    private static volatile RetrofitClient mInstance;

    private Retrofit retrofit;

    public RetrofitClient() {
    }


    public static RetrofitClient getInstance() {
        if (mInstance == null) {
            synchronized (RetrofitClient.class) {
                if (mInstance == null) {
                    mInstance = new RetrofitClient();
                }
            }
        }
        return mInstance;
    }

    //请求超时时间5S
    private Long connectionTimeoutTime = 60L;

    public OkHttpClient okHttpClient() {
        HttpLoggingInterceptorM interceptorLogging = new HttpLoggingInterceptorM(new LogInterceptor());
        interceptorLogging.setLevel(HttpLoggingInterceptorM.Level.BODY);
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
//                .addInterceptor(new HttpInterceptor())
                .addInterceptor(interceptorLogging)
                .connectTimeout(connectionTimeoutTime, TimeUnit.SECONDS)//链接超时设置
                .readTimeout(connectionTimeoutTime, TimeUnit.SECONDS)//读取超时时间设置
                .writeTimeout(connectionTimeoutTime, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)//默认重试一次 若需要重试N次则要实现拦截器
                .build();
        return okHttpClient;
    }


    public <T> T getService(Class<T> cls) {
        return getRetrofit().create(cls);
    }

    private synchronized Retrofit getRetrofit() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl("")
                    .callFactory(okHttpClient())
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
        } else {
            retrofit = retrofit.newBuilder().baseUrl("").build();
        }
        return retrofit;
    }
}
